package org.potiorb.demo.generated;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

import org.potiorb.orb.ORBImpl;
import org.potiorb.orb.giop.GIOPMessageReply;
import org.potiorb.orb.giop.GIOPMessageRequest;
import org.potiorb.orb.invoke.Invoker;
import org.potiorb.orb.marshal.Any;
import org.potiorb.orb.marshal.CallData;
import org.potiorb.orb.marshal.Marshaler;
import org.potiorb.orb.marshal.ParamData;
import org.potiorb.orb.marshal.ParamMode;
import org.potiorb.orb.marshal.TCKind;
import org.potiorb.orb.marshal.TypeCodeImpl;
import org.potiorb.orb.portable.ObjectImpl;
import org.potiorb.orb.portable.ObjectRef;

/**
 *	Generated from IDL definition of interface "Teste"
 *	@author JacORB IDL compiler
 */


public class _TesteStub extends ObjectImpl implements Teste, ITesteStubSOAP
{
	private String[] ids = {"IDL:Teste:1.0","IDL:omg.org/CORBA/Object:1.0"};
	public String[] _ids()
	{
		return ids;
	}

	public final static java.lang.Class _opsClass = TesteOperations.class;
	public void simples_hello(java.lang.String texto)
	{
		ObjectRef _ref = (ObjectRef)this._get_delegate();

		ParamData _paramslist[] = new ParamData[1];
		ParamData _param = new ParamData();
		_param.setParamMode(new ParamMode(ParamMode._pm_IN));
		_param.setTypeCode(new TypeCodeImpl(TCKind.tk_string));
		_paramslist[0] =_param;

		CallData _call = new CallData();
		_call.setMethodName("simples_hello");
		_call.setNoOfParameters(1);
		_call.setParamerers(_paramslist);

		Any _value_param = new Any();
		_value_param.insert_string(texto);
                ORBImpl _orb = _ref.getOrb();
                Marshaler mar =  _orb.getMarshaler();
		GIOPMessageRequest message = mar.MarshalInvocationRequest(_ref,_call, _value_param);
                Invoker inv = _orb.getInvoker();
                GIOPMessageReply _replymsg = inv.Invoke(message,_ref);
		_ref.getOrb().getMarshaler().UnmarshalInvocationReply(_replymsg);
	}
	
	@Override
	public String timeAsString() throws Exception {
		
		ObjectRef _ref = (ObjectRef)this._get_delegate();
		ORBImpl orb = _ref.getOrb();
		Marshaler mar = orb.getMarshaler();
		
		String response = "";
		
        try {
        	/**
        	 * Tratando a MSG de responsta do webservice
        	 */
        	String xml = "<?xml version=\"1.0\" ?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns2:getTimeAsString xmlns:ns2=\"http://exe/\"/></soap:Body></soap:Envelope>";
			response = postHttp("http://localhost:9876/ts/exe/getTimeAsString", xml);
			
			System.out.println("Método getTimeAsString");
        	System.out.println("\nXML de envio para o webService\n"+xml);
        	System.out.println("\nXML de resposta do webService\n"+response);
        	
			SOAPMessage msgResponse = mar.create_soap_message(response);
			return mar.extract_contents_string(msgResponse);
		} catch (Exception e) {
			throw new Exception("Tratando resposta no _TesteStub errada", e);
		}
	}
	
	@Override
	public long timeAsElapsed() throws Exception {
		ObjectRef _ref = (ObjectRef)this._get_delegate();
		ORBImpl orb = _ref.getOrb();
		Marshaler mar = orb.getMarshaler();
		
		String response = "";
		
        try {
        	/**
        	 * Tratando a MSG de responsta do webservice
        	 */
        	String xml = "<?xml version=\"1.0\" ?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns2:getTimeAsElapsed xmlns:ns2=\"http://exe/\"/></soap:Body></soap:Envelope>";
			response = postHttp("http://localhost:9876/ts/exe/getTimeAsElapsed", xml);
			
			System.out.println("-------------------------------------------------------------------------------------");
			System.out.println("\nMétodo getTimeAsElapsed()");
        	System.out.println("\nXML de envio para o webService\n"+xml);
        	System.out.println("\nXML de resposta do webService\n"+response);
			
			SOAPMessage msgResponse = mar.create_soap_message(response);
			return Long.parseLong(mar.extract_contents_string(msgResponse));
		} catch (Exception e) {
			throw new Exception("Tratando resposta no _TesteStub errada", e);
		}
		
	}

	private String postHttp(String url, String SOAPMsg) throws Exception {
		URL endereco = null;
		HttpURLConnection conn = null;
		try {
			
			/**
			 * Abrindo conexão e setando parametros da mesma
			 */
			endereco = new URL(url);
			conn = (HttpURLConnection) endereco.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
			
			/**
			 * Enviando requisição para o webservice via POST/HTTP
			 */
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(SOAPMsg);
			wr.flush();
			
			/**
			 * Recebendo resposta do webservice
			 */
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			StringBuilder resposta = new StringBuilder();
			String line;
			while ((line = rd.readLine()) != null){
				resposta.append(line);
			}
			wr.close();
			rd.close();
			return resposta.toString();
		} catch (MalformedURLException e) {
			throw new Exception("URL errada!", e);
		}
	}
	

	
}
